// 插件类
import {hex_md5} from "@/utils/md5";
import * as echarts from "echarts";
import {generateChartRenderOption, chartOptions} from "@/utils/charts";
import axios from 'axios'

/**
 * 远程请求插件工具
 */
class RemoteRequestPlugin {
    // 插件名称
    name = 'http';
    // 请求url
    url = null;
    // api ID
    apiId = null;
    // 类型
    type = null;
    // 图表类型
    chartType = null;

    constructor() {
    }

    // 插件名称, 必须存在的属性
    get name() {
        return this.name
    }

    // 请求基本url
    get url() {
        return this.url
    }

    /**
     * 词法分析后处理函数, 用于根据当前plugin token处理其他token, 实现类似装饰器的效果.
     *
     * @param {Object} context 上下文, 即markdown.context
     * @param {Object} token 当前plugin的 token
     * @param {Number} index 当前的token数组下表
     * @param {Array<Object>} tokens token数组
     *
     * @returns {Array<Object>} 处理后的token数组
     */
    token(context, token, index, tokens) {
        if (token.args) {
            let tmp = token.args.split(',')
            this.apiId = tmp[0]
            this.type = tmp[1]
            if (this.type === 'chart') {
                this.chartType = tmp[2]
            }
        }
        // 必须返回一个token数组
        return tokens
    }

    /**
     * 渲染函数, 用于将插件渲染成字符串.
     *
     * @param {Object} context 上下文, 即markdown.context
     * @param {Object} token 当前的plugin token
     *
     * @returns {String} 渲染结果
     */
    // eslint-disable-next-line
    async render(context, token, that) {
        let tmpResult = ''
        if (this.apiId) {
            async function getResult(apiId) {
                const {data} = await axios({
                    url: 'https://www.fastmock.site/mock/fa928434a2dd871951382d8d8b3a1cda/project/sqlpanel/apis/execute/' + apiId,
                    method: 'get',
                    params: null
                })
                return data
            }

            if (token.args) {
                let tmp = token.args.split(',')
                this.apiId = tmp[0];
                this.type = tmp[1]
                if (this.type === 'chart') {
                    this.chartType = tmp[2]
                }
                const _list = await getResult(tmp[0]);
                const {columns, dataList} = _list, curId = hex_md5(token.args)
                tmpResult = ''
                let curElement = document.getElementById(curId);
                if (tmp[1] === 'table') {
                    tmpResult = getTableHtml(columns, dataList)
                    if (curElement) {
                        curElement.innerHTML = tmpResult
                    }
                } else if (tmp[1] === 'chart') {
                    renderChart(columns, dataList, curId, curElement, tmp[2], tmp[3], tmp[4])
                } else if (tmp[1] === 'script') {
                    executeScript(columns, dataList, curId, curElement, tmp[2], tmp, token)
                } else if (tmp[1] === 'number') {

                } else {
                    tmpResult = ''
                }
            }
        }
        return tmpResult
    }
}

function getTableHtml(columns, dataList) {
    let t1 = '', t2 = ''
    for (let i = 0, len = columns.length; i < len; i++) {
        t1 += '<th>' + columns[i].name + '</th>'
    }
    for (let i = 0, len = dataList.length; i < len; i++) {
        let t3 = '', item = dataList[i]
        for (let i = 0, len = columns.length; i < len; i++) {
            t3 += '<td>' + item[columns[i].name] + '</td>'
        }
        t2 += '<tr>' + t3 + '</tr>'
    }
    return `
        <div class="pure-table pure-table-bordered">
            <table>
                <thead>
                    <tr>${t1}</tr>
                </thead>
                <tbody>
                ${t2}
                </tbody>
            </table>
        </div>
    `
}

function renderChart(columns, dataList, curId, curElement, chartType, x, y) {
    if (!curElement) {
        curElement = document.getElementById(curId);
    }
    let setting = chartOptions.find(n => n.key === chartType.trim());
    if (!curElement || !setting) {
        throw new Error(`没有找到当前的html节点${curId}或者不支持当前的图示类型${chartType}`)
    }
    curElement.style.height = '300px';
    curElement.style.textAlign = 'center';
    if (x && y) {
        setting.options[0].value = x
        setting.options[1].value = y
    } else {
        setting.options[0].value = columns[0].name
        setting.options[1].value = columns[1].name
    }
    let myChart = echarts.init(curElement)
    myChart.showLoading();
    let option = generateChartRenderOption(dataList, setting)
    myChart.setOption(option, true)
    myChart.hideLoading();
    myChart.resize()
    window.addEventListener('resize', () => {
        myChart.resize()
    })

}

function executeScript(columns, dataList, curId, curElement, scriptType, argsArr, token) {
    if (!curElement) {
        curElement = document.getElementById(curId);
    }
    if (!curElement) {
        throw new Error(`没有找到当前的html节点${curId}!`)
    }
    const script = token.script, funcStr = 'function(columns,dataList)' + script, scriptFunc = new Function(funcStr)();
    let funcResult = scriptFunc()

    if (scriptType === 'html') {
        curElement.innerHTML = funcResult
    } else if (scriptType === 'chart') {

    } else {
        curElement.innerText = token.script
    }
}

export default RemoteRequestPlugin